<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket集群测试页面</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
        }
        .connection-status {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
            text-align: center;
        }
        .connected {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .disconnected {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input, textarea, button {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            background-color: #007bff;
            color: white;
            cursor: pointer;
            margin-top: 10px;
        }
        button:hover {
            background-color: #0056b3;
        }
        button:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
        .messages {
            height: 300px;
            overflow-y: auto;
            border: 1px solid #ddd;
            padding: 10px;
            background-color: #f8f9fa;
            border-radius: 4px;
            margin-top: 15px;
        }
        .message {
            margin-bottom: 10px;
            padding: 8px;
            border-radius: 4px;
            background-color: white;
            border-left: 4px solid #007bff;
        }
        .message-time {
            font-size: 0.8em;
            color: #6c757d;
        }
        .tabs {
            display: flex;
            margin-bottom: 20px;
        }
        .tab {
            padding: 10px 20px;
            background-color: #e9ecef;
            border: none;
            cursor: pointer;
            flex: 1;
            text-align: center;
        }
        .tab.active {
            background-color: #007bff;
            color: white;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>WebSocket集群测试</h1>
        
        <div id="connectionStatus" class="connection-status disconnected">
            未连接
        </div>
        
        <div class="form-group">
            <label for="userId">用户ID:</label>
            <input type="text" id="userId" placeholder="输入用户ID" value="user1">
        </div>
        
        <div class="form-group">
            <button id="connectBtn">连接</button>
            <button id="disconnectBtn" disabled>断开连接</button>
        </div>
        
        <div class="tabs">
            <button class="tab active" data-tab="send">发送消息</button>
            <button class="tab" data-tab="broadcast">广播消息</button>
            <button class="tab" data-tab="heartbeat">心跳检测</button>
        </div>
        
        <div id="sendTab" class="tab-content active">
            <div class="form-group">
                <label for="targetUserId">目标用户ID (可选):</label>
                <input type="text" id="targetUserId" placeholder="输入目标用户ID以发送私信">
            </div>
            <div class="form-group">
                <label for="messageContent">消息内容:</label>
                <textarea id="messageContent" rows="3" placeholder="输入要发送的消息"></textarea>
            </div>
            <button id="sendMessageBtn" disabled>发送消息</button>
        </div>
        
        <div id="broadcastTab" class="tab-content">
            <div class="form-group">
                <label for="broadcastContent">广播消息内容:</label>
                <textarea id="broadcastContent" rows="3" placeholder="输入要广播的消息"></textarea>
            </div>
            <button id="broadcastMessageBtn" disabled>广播消息</button>
        </div>
        
        <div id="heartbeatTab" class="tab-content">
            <div class="form-group">
                <button id="heartbeatBtn" disabled>发送心跳</button>
                <div id="heartbeatStatus"></div>
            </div>
        </div>
        
        <div class="messages" id="messagesContainer">
            <div class="message">
                <div>系统消息：WebSocket客户端已就绪</div>
                <div class="message-time">--:--:--</div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/stompjs@2.3.3/lib/stomp.min.js"></script>
    <script>
        let stompClient = null;
        let userId = null;
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 绑定事件
            document.getElementById('connectBtn').addEventListener('click', connect);
            document.getElementById('disconnectBtn').addEventListener('click', disconnect);
            document.getElementById('sendMessageBtn').addEventListener('click', sendMessage);
            document.getElementById('broadcastMessageBtn').addEventListener('click', broadcastMessage);
            document.getElementById('heartbeatBtn').addEventListener('click', sendHeartbeat);
            
            // 绑定Tab切换事件
            document.querySelectorAll('.tab').forEach(tab => {
                tab.addEventListener('click', function() {
                    // 移除所有活动状态
                    document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
                    document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
                    
                    // 添加当前活动状态
                    this.classList.add('active');
                    const tabId = this.getAttribute('data-tab');
                    document.getElementById(tabId + 'Tab').classList.add('active');
                });
            });
            
            // 更新时间显示
            setInterval(updateMessageTimes, 60000);
        });
        
        // 连接到WebSocket服务器
        function connect() {
            userId = document.getElementById('userId').value.trim();
            if (!userId) {
                showMessage('请输入用户ID', 'error');
                return;
            }
            
            // 构建WebSocket连接URL
            const socket = new SockJS('http://127.0.0.1:20001/ws?userId=' + encodeURIComponent(userId), null, {
                headers: {
                    'X-User-Id': userId
                }
            });
            stompClient = Stomp.over(socket);
            
            // 连接并订阅消息
            stompClient.connect({login: userId}, function(frame) {
                showMessage('已连接到WebSocket服务器: ' + frame, 'success');
                document.getElementById('connectionStatus').className = 'connection-status connected';
                document.getElementById('connectionStatus').textContent = '已连接';
                document.getElementById('connectBtn').disabled = true;
                document.getElementById('disconnectBtn').disabled = false;
                document.getElementById('sendMessageBtn').disabled = false;
                document.getElementById('broadcastMessageBtn').disabled = false;
                document.getElementById('heartbeatBtn').disabled = false;
                
                // 订阅用户特定消息
                stompClient.subscribe('/user/queue/messages', function(message) {
                    const msg = JSON.parse(message.body);
                    showMessage(`收到消息 [${msg.senderUserId}]: ${msg.content}`, 'info');
                });
                
                // 订阅心跳响应
                stompClient.subscribe('/user/queue/heartbeat', function(message) {
                    showMessage('收到心跳响应: ' + message.body, 'info');
                    document.getElementById('heartbeatStatus').innerHTML = 
                        '<span style="color: green;">心跳正常: ' + new Date().toLocaleTimeString() + '</span>';
                });
            }, function(error) {
                showMessage('连接失败: ' + error, 'error');
                document.getElementById('connectionStatus').className = 'connection-status disconnected';
                document.getElementById('connectionStatus').textContent = '连接失败';
            });
        }
        
        // 断开连接
        function disconnect() {
            if (stompClient !== null) {
                stompClient.disconnect();
            }
            
            showMessage('已断开连接', 'info');
            document.getElementById('connectionStatus').className = 'connection-status disconnected';
            document.getElementById('connectionStatus').textContent = '已断开连接';
            document.getElementById('connectBtn').disabled = false;
            document.getElementById('disconnectBtn').disabled = true;
            document.getElementById('sendMessageBtn').disabled = true;
            document.getElementById('broadcastMessageBtn').disabled = true;
            document.getElementById('heartbeatBtn').disabled = true;
        }
        
        // 发送消息
        function sendMessage() {
            if (!stompClient || !stompClient.connected) {
                showMessage('WebSocket未连接', 'error');
                return;
            }
            
            const content = document.getElementById('messageContent').value.trim();
            if (!content) {
                showMessage('请输入消息内容', 'error');
                return;
            }
            
            const targetUserId = document.getElementById('targetUserId').value.trim();
            
            const message = {
                type: 'CHAT',
                content: content,
                senderUserId: userId,
                targetUserId: targetUserId || null,
                timestamp: new Date()
            };
            
            stompClient.send("/app/chat.send", {}, JSON.stringify(message));
            showMessage(`发送消息: ${content}`, 'sent');
            document.getElementById('messageContent').value = '';
        }
        
        // 广播消息
        function broadcastMessage() {
            if (!stompClient || !stompClient.connected) {
                showMessage('WebSocket未连接', 'error');
                return;
            }
            
            const content = document.getElementById('broadcastContent').value.trim();
            if (!content) {
                showMessage('请输入广播消息内容', 'error');
                return;
            }
            
            const message = {
                type: 'BROADCAST',
                content: content,
                senderUserId: userId,
                timestamp: new Date()
            };
            
            stompClient.send("/app/chat.broadcast", {}, JSON.stringify(message));
            showMessage(`广播消息: ${content}`, 'sent');
            document.getElementById('broadcastContent').value = '';
        }
        
        // 发送心跳
        function sendHeartbeat() {
            if (!stompClient || !stompClient.connected) {
                showMessage('WebSocket未连接', 'error');
                return;
            }
            
            stompClient.send("/app/chat.heartbeat", {}, JSON.stringify({}));
            document.getElementById('heartbeatStatus').innerHTML = 
                '<span style="color: orange;">发送心跳...</span>';
        }
        
        // 显示消息
        function showMessage(content, type) {
            const messagesContainer = document.getElementById('messagesContainer');
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message';
            
            const timeDiv = document.createElement('div');
            timeDiv.className = 'message-time';
            const now = new Date();
            timeDiv.textContent = now.toLocaleTimeString();
            
            messageDiv.innerHTML = `<div>${content}</div>`;
            messageDiv.appendChild(timeDiv);
            
            // 根据消息类型设置样式
            switch(type) {
                case 'error':
                    messageDiv.style.borderLeftColor = '#dc3545';
                    break;
                case 'success':
                    messageDiv.style.borderLeftColor = '#28a745';
                    break;
                case 'sent':
                    messageDiv.style.borderLeftColor = '#007bff';
                    break;
                case 'info':
                default:
                    messageDiv.style.borderLeftColor = '#17a2b8';
                    break;
            }
            
            messagesContainer.appendChild(messageDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }
        
        // 更新消息时间显示
        function updateMessageTimes() {
            const timeElements = document.querySelectorAll('.message-time');
            const now = new Date();
            
            timeElements.forEach(element => {
                // 只更新相对时间显示，不更新具体时间戳
                // 这里简化处理，实际项目中可能需要更复杂的时间处理逻辑
            });
        }
    </script>
</body>
</html>